import React from 'react'
import {Success,Info,Warning} from 'lib/components/Notify.jsx'
import View from 'lib/View.jsx'
import basicInfo from '../apis/basicInfo'
import {Dialog} from '../setting/VersionListView.jsx'
import _ from 'underscore'
import $ from 'jquery'
import $form from 'jquery-form'
import dispatcher from 'lib/dispatcher'

class Dialog2 extends Dialog {
  submit() {
    if(this.state.saving) {
      return ;
    }

    if(!this.state.uploadFileStore.getFiles().length){
      this.setState({
        msg:'请选择上传文件'
      })
      return ;
    }

    this.setState({saving:true});

    $(this.refs.form).ajaxSubmit({
      dataType:'json'
    }).data('jqxhr').then(res => {
      if(res.result) {
        Success('上传成功');
        this.close()
        dispatcher.dispatch({
          $type:'file_uploaded',
          version:res.mappingfile.appVersionName
        });
      } else {
        this.setState({
          msg:res.msg,
          saving:false
        });
      }
    }, err => {
      this.setState({
        msg:err.responseJSON?err.responseJSON.message:'Error',
        saving:false
      })
    });
  }
}

export default class ConfusedConfig extends View {

  constructor(props, context) {
    super(props, context);

    this.state = {
      list: [],
      fileList: []
    };
    this.uploadedVersionList = [];

    this.listApi = basicInfo({
      urlName:'app',
      parentId:BlueWare.appId,
      appId:null
    });

    $.ajax({
      url:BlueWare.urlPrefix + '/app/' + BlueWare.appId + '/listDsym.json',
      dataType:'json'
    }).done(data => {
      this.setState({fileList: data});
    });

    this.file_uploaded = this.file_uploaded.bind(this);
  }

  file_uploaded(payload) {
    if (payload.$type === 'file_uploaded') {
      this.uploadedVersionList.push(payload.version);
    }
  }

  componentDidMount() {
    this.__register = dispatcher.register(this.file_uploaded);

    this.listApi.fetch().done(data => {
      this.setState({list:data.result});
    });
  }

  componentWillUnmount() {
    if (this.__register) {
      dispatcher.unregister(this.__register);
      delete this.__register;
    }
  }

  showDialog(){
    let data = _.filter(this.state.list, item =>
      !(_.contains(this.uploadedVersionList, item.name) || _.findWhere(this.state.fileList, {appVersionId:item.id})), this);
    if(data.length){
      Dialog2.mount({
        versionList: data
      })
    } else {
      Info(function(notice){
        return (
          <div>
            目前所有版本都已存在符号化文件，请先到<a href="setting">应用设置</a>删除需要重新上传的文件。
          </div>
        )
      });
    }
  }

  render() {
    let currentStyle = {'marginTop':'5px'};
    return (
      <button
        className="btn-green btn-sm"
        style={_.extend(currentStyle, this.props.style)}
        type="button"
        onClick={this.showDialog.bind(this)}>
        上传 dSYM 文件
      </button>
    );
  }
}

ConfusedConfig.defaultProps = {
  style:{}
}
